package com.vhall.component.service.lottery.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.vhall.component.dao.lottery.LotteryMapper;
import com.vhall.component.dao.lottery.LotteryRecordMapper;
import com.vhall.component.entity.lottery.entity.LotteryAwardEntity;
import com.vhall.component.entity.lottery.entity.LotteryEntity;
import com.vhall.component.entity.lottery.entity.LotteryRecordEntity;
import com.vhall.component.entity.lottery.vo.AwardVO;
import com.vhall.component.entity.lottery.vo.LotteryEndReqVO;
import com.vhall.component.entity.lottery.vo.LotteryRspVO;
import com.vhall.component.framework.common.exception.BusinessException;
import com.vhall.component.plugin.common.exception.BizErrorCode;
import com.vhall.component.service.lottery.LotteryRecordService;
import com.vhall.component.service.lottery.common.Consts;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

/**
 * @author longzhen.gong
 * @date 2021/7/13 20:14
 */
@Slf4j
@Service
public class LotteryRecordServiceImpl implements LotteryRecordService {

    @Autowired
    private LotteryMapper lotteryMapper;

    @Autowired
    private LotteryRecordMapper lotteryRecordMapper;

    @Override
    public LotteryRspVO end(LotteryEndReqVO reqVo) {
        LotteryEntity lottery = lotteryMapper.selectById(reqVo.getLotteryId());
        if (lottery == null) {
            throw new BusinessException(BizErrorCode.COMP_LOTTERY_NOT_FOUND);
        }
        if (Consts.LOTTERY_STATUS_END == lottery.getLotteryStatus()) {
            throw new BusinessException(BizErrorCode.COMP_LOTTERY_HAS_ENDED);
        }
        lottery.setLotteryStatus(Consts.LOTTERY_STATUS_END);
        lottery.setUpdatedAt(LocalDateTime.now());
        lotteryMapper.updateById(lottery);

        //组装响应类
        List<LotteryRecordEntity> userRspVos = lotteryRecordMapper.selectList(
                Wrappers.<LotteryRecordEntity>lambdaQuery()
                        .eq(LotteryRecordEntity::getLotteryId, lottery.getId()));
        LotteryRspVO rspVo = new LotteryRspVO();
        BeanUtils.copyProperties(lottery, rspVo);
        rspVo.setLotteryUsers(userRspVos);
        //rspVo.setAwardSnapshot(getAwardSnapShoot(lottery.getAwardSnapshoot()));
        return rspVo;
    }

    private AwardVO getAwardSnapShoot(String snapshoot) {
        if (StringUtils.isNotBlank(snapshoot)) {
            LotteryAwardEntity award = JSON.parseObject(snapshoot, LotteryAwardEntity.class);
            AwardVO awardVO = new AwardVO();
            BeanUtils.copyProperties(award, awardVO);
            return awardVO;
        }
        return null;
    }


}
